package com.ww.demo.thread.d4;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class ReentrantReadWriteLockDemo {

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public static void main(String[] args) {
        ReentrantReadWriteLockDemo demo = new ReentrantReadWriteLockDemo();
        new Thread(() -> demo.read(), "ThreadA").start();
        new Thread(() -> demo.read(), "ThreadB").start();

        new Thread(() -> demo.write(), "ThreadC").start();
        new Thread(() -> demo.write(), "ThreadD").start();
    }

    /**
     * 读读
     * 共享
     */
    private void read(){
        lock.readLock().lock();
        System.out.println("获得读锁" + Thread.currentThread().getName() + "时间:" + System.currentTimeMillis());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 写写
     * 互斥
     */
    private void write(){
        lock.writeLock().lock();
        System.out.println("获得写锁" + Thread.currentThread().getName() + "时间:" + System.currentTimeMillis());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
          lock.writeLock().unlock();
        }
    }

}
